package com.hao.crm.web.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hao.crm.domain.Employee;
import com.hao.crm.util.PermissionUtil;
import com.hao.crm.util.UserContext;

public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		UserContext.set(request);
		Employee e = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
		if(e==null) {
			response.sendRedirect("/login.jsp");
			return false;
		}
		//URL权限控制，将请求变为权限表达式
		if(handler instanceof HandlerMethod) {
			
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Object bean = handlerMethod.getBean();
			Method method = handlerMethod.getMethod();
			String function = bean.getClass().getName()+":"+method.getName();
			if(PermissionUtil.checkPermission(function)) {
				return true;
			}else {
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
